import { defineStore } from 'pinia'

// 购物车状态管理
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [] // 购物车商品列表
  }),
  getters: {
    // 获取购物车商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => {
        return total + (item.selected ? item.quantity : 0)
      }, 0)
    },
    // 获取选中商品的总金额
    totalAmount: (state) => {
      return state.items.reduce((total, item) => {
        return total + (item.selected ? item.price * item.quantity : 0)
      }, 0)
    },
    // 获取选中的商品列表
    selectedItems: (state) => {
      return state.items.filter(item => item.selected)
    },
    // 是否全选
    isAllSelected: (state) => {
      return state.items.length > 0 && state.items.every(item => item.selected)
    }
  },
  actions: {
    // 添加商品到购物车
    addToCart(product, quantity = 1) {
      const existingItem = this.items.find(
        item => item.id === product.id && item.attributes === product.attributes
      )
      
      if (existingItem) {
        // 如果商品已存在，增加数量
        existingItem.quantity += quantity
      } else {
        // 否则添加新商品
        this.items.push({
          ...product,
          quantity,
          selected: true
        })
      }
    },
    
    // 从购物车移除商品
    removeFromCart(index) {
      this.items.splice(index, 1)
    },
    
    // 清空购物车
    clearCart() {
      this.items = []
    },
    
    // 修改商品数量
    updateQuantity(index, quantity) {
      if (quantity > 0) {
        this.items[index].quantity = quantity
      }
    },
    
    // 切换商品选中状态
    toggleSelection(index) {
      this.items[index].selected = !this.items[index].selected
    },
    
    // 全选/取消全选
    toggleAllSelection(selected) {
      this.items.forEach(item => {
        item.selected = selected
      })
    },
    
    // 批量删除选中的商品
    removeSelectedItems() {
      this.items = this.items.filter(item => !item.selected)
    }
  },
  // 持久化配置
  persist: {
    key: 'ai-shop-cart',
    storage: localStorage,
    paths: ['items']
  }
})